<?php
namespace app\common\bonus;

Class Common
{

	protected $error;

	public function getError(){
		return $this->error;
	}

	// 累计奖金
	protected function incTotal($bonus,$uid,$day,$bonus_name){
		// 累计该日奖金
		if(true!==model('bonus_member_daily')->incDayBonus($uid,$day,$bonus_name,$bonus)){
			exception('累计会员当日奖金出错！');
		}
		// 累计奖金总数
		if(true!==model('bonus_member_total')->incMemberBonus($uid,$bonus_name,$bonus)){
			exception('累计会员奖金总数出错！');
		}
		return true;
	}
	/**
	 * 货币分配明细记录
	 * @param  [type] $coinConfig  [description]
	 * @param  [type] $bonus_name  [description]
	 * @param  [type] $reason_uid  [description]
	 * @param  [type] $effect_uid  [description]
	 * @param  [type] $bonus       [description]
	 * @param  [type] $reason_time [description]
	 * @return [type]              [description]
	 */
	protected function bonus_record($coinConfig,$bonus_name,$reason_uid,$effect_uid,$bonus,$reason_time,$tip=''){
		$bonus_tag = [
			'lingshou' => '零售利润',
			'xiaoshou' => '销售补贴',
			'guanli' => '管理补贴',
			'fuwu' => '服务补贴'
		];
		$record = [];
		foreach($coinConfig as $config):
			$record[] = [
				'bonus_name' => $bonus_name,
				'reason_uid' => $reason_uid,
				'effect_uid' => $effect_uid,
				'coin_id' => $config['coin_id'],
				'amount' => $bonus*$config['config']/100,
				'remark' => '用户['.$reason_uid.']产生'.$bonus.$bonus_tag[$bonus_name].$tip,
				'reason_time' => $reason_time,
			];
		endforeach;
		if(!model('bonus_record')->saveAll($record)){
			exception('插入奖金分配明细出错！');
		}
		return true;
	}

	/**
	 * 比较封顶值
	 * @param  [type] $uid         [description]
	 * @param  [type] $bonus       [description]
	 * @param  [type] $max         [description]
	 * @param  [type] $reason_time [description]
	 * @return [type]              [description]
	 */
	protected function mathMax($bonus_name,$uid,$bonus,$max,$reason_time){
		// 获取当前当日总奖金
		$day = date('Ymd',$reason_time);
		$day_total = model('bonus_member_daily')->where(['uid'=>$uid,'day'=>$day,'bonus_name'=>$bonus_name])->value('total');
		if(!$day_total) $day_total=0;
		// 如果累加奖金大于封顶值，累加奖金等于封顶值，那么净增值等于封顶值减去之前总额；否则净增值等于新增奖金。
		$inc_bonus = ($day_total+$bonus)>$max ? $max-$day_total : $bonus;
		$tip = '';
		if($inc_bonus!=$bonus){
			$tip = '[当日奖金超过封顶值]';
		}
		return [
			'inc_bonus' => $inc_bonus,
			'tip' => $tip
		];
			
	}

}